import Vue from 'vue'
import VueRouter from 'vue-router'
Vue.use(VueRouter)
import routes from './router'
//引入store
import store from '@/store/index'
//解决路由跳转时的NavigationDuplicated错误
// 缓存原型上的push函数
const originPush = VueRouter.prototype.push
const originReplace = VueRouter.prototype.replace
// 给原型对象上的push指定新函数函数
VueRouter.prototype.push = function (location, resolve, reject) {
  if (resolve && reject) {
    // 如果有指定任意回调函数, 通过call调用源push函数处理
    originPush.call(this, location, resolve, reject)
  } else {
    originPush.call(
      this,
      location,
      () => {},
      () => {}
    )
  }
}
VueRouter.prototype.replace = function (location, resolve, reject) {
  if (resolve && reject) {
    originReplace.call(this, location, resolve, reject)
  } else {
    originReplace.call(
      this,
      location,
      () => {},
      () => {}
    )
  }
}

const router = new VueRouter({
  routes,
  //切换路由时滚动条回到顶部
  scrollBehavior(to, from, savedPosition) {
    return { y: 0 }
  }
})

//全局前置守卫
router.beforeEach(async (to, from, next) => {
  let token = store.state.user.token
  let name = store.state.user.userInfo.name
  let toPath = to.path
  if(token){
    //已经登录而且还想去登录------不行
    if(toPath=="/login"||toPath=='/register'){
       next('/');
    }else{
      //已经登陆了,访问的是非登录与注册
      //登录了且拥有用户信息放行
      if(name){
        next();
      }else{
        //登陆了且没有用户信息
        //在路由跳转之前获取用户信息且放行
        try {
         await store.dispatch('getUserInfo');
         next();
        } catch (error) {
          //token失效从新登录
          await store.dispatch('userLogout');
          next('/login')
        }
      }
    }
  }else {
    //如果没有登陆
    // 无法去支付，交易，个人中心相关页面
    if (
      toPath.indexOf('/trade') != -1 ||
      toPath.indexOf('/pay') != -1 ||
      toPath.indexOf('/center') != -1
    ) {
      //把未登录的时候向去而没有去成的信息，存储于地址栏中【路由】
      next('/login?redirect='+toPath);
    } else {
      next()
    }
  }
})

export default router
